package com.wondertek.poms.core.utils;

import com.luciad.imageio.webp.WebPWriteParam;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author gaozhengxing gaozhenghang@wondertek.com.cn
 * @date 2021/1/4 19:07
 * @description TODO
 */
@Slf4j
public class SyncImageUtil {
    /**
     * @param srcImageFile 源文件
     * @param result	转码后的文件
     * @param width
     * @param height
     * @param bb
     * @param fileType
     * @param destFoderPath
     * @return
     */
    public final static boolean scaleImage(String srcImageFile, String result, int width, int height, boolean bb, String fileType, String destFoderPath) {
        boolean bSuc = false;
        //1.检查目标文件夹是否存在，不存在则创建
        File dirFile = new File(destFoderPath);
        if (!dirFile.isDirectory()) {
            dirFile.mkdirs();
        }
        ImageOutputStream ios = null;
        try {
            //2.获取原图片的宽和高
            BufferedImage srcImg = ImageIO.read(new File(srcImageFile));
            int srcWidth = srcImg.getWidth(null);
            int srcHeight = srcImg.getHeight(null);

            float ratio = 1.0f;
            float widthRatio = (float)width/srcWidth;
            float heightRatio = (float)height/srcHeight;
            if(widthRatio<1.0 || heightRatio<1.0) {
                ratio = (widthRatio<=heightRatio) ? widthRatio : heightRatio;
            }
            int newWidth = (int) (ratio * srcWidth);
            int newHeight = (int) (ratio * srcHeight);
            if (fileType.equals("webp")){
                BufferedImage targetImg = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = targetImg.createGraphics();
                graphics.drawImage(srcImg.getScaledInstance(newWidth, newHeight, Image.SCALE_AREA_AVERAGING), 0, 0, newWidth, newHeight, Color.white, null);
                graphics.dispose();

                //卷积核(权矩阵)
                float[] kernelData2 = {-0.125f, -0.125f, -0.125f, -0.125f, 2, -0.125f, -0.125f, -0.125f, -0.125f };
                Kernel kernel = new Kernel(3, 3, kernelData2);
                ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
                targetImg = cOp.filter(targetImg, null);

                // Obtain a WebP ImageWriter instance
                ImageWriter imageWriter = ImageIO.getImageWritersByMIMEType("image/webp").next();
                ios = ImageIO.createImageOutputStream(new FileOutputStream(result));
                imageWriter.setOutput(ios);

                // Configure encoding parameters
                WebPWriteParam writeParam = new WebPWriteParam(imageWriter.getLocale());
                writeParam.setCompressionMode(WebPWriteParam.MODE_EXPLICIT);

                // Encode
                IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(targetImg), null);
                WebPWriteParam webpParams  =  (WebPWriteParam) imageWriter.getDefaultWriteParam();
                webpParams.setCompressionMode(WebPWriteParam.MODE_EXPLICIT);
                //webpParams.setCompressionType("");
                //webpParams.setCompressionQuality(0.75f);

                imageWriter.write(imageMetaData, new IIOImage(targetImg, null, null), writeParam);
                imageWriter.dispose();
                //ImageIO.write(targetImg, "webp", new File(result));
            }else{
                // 1、先转换成jpg
                Thumbnails.of(srcImageFile).scale(1.0f).toFile(result);
                //压缩
                Thumbnails.of(result).size(newWidth, newHeight).outputQuality(0.75).toFile(result);

//				ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpg").next();
//				ios = ImageIO.createImageOutputStream(new FileOutputStream(result));
//				imageWriter.setOutput(ios);
//
//				IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(targetImg), null);
//				JPEGImageWriteParam jpegParams  =  (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
//				jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
//				jpegParams.setCompressionQuality(0.75f);
//
//				imageWriter.write(imageMetaData, new IIOImage(targetImg, null, null), null);
//				imageWriter.dispose();
            }
            bSuc = true;
            log.info("原图" + srcImageFile + "|新的图片" + result + "|转码结果：" + bSuc);
        } catch (Exception e) {
            log.error("原图" + srcImageFile + "|新的图片" + result + "|转码结果：" + bSuc, e);
        } finally {
            if(ios != null) {
                try {
                    ios.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return bSuc;
    }

}
